import json

from django_redis import get_redis_connection

from powers_of_ten.utils.fastdfs.fastdfs_storage import FastDFSStorage
from django.contrib.auth.models import AnonymousUser
from django.http import JsonResponse, response
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import RetrieveAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from person.models import User
from spit.serializer import SpitSerializer
from spit.utils import transfer
from .models import Spit
from django.views import View


# 6.1 吐槽列表 　＆　　6.4 发布吐槽
class SpitListView(APIView):

    # 6.1 吐槽列表
    def get(self, request):
        spits = Spit.objects.filter(parent__isnull=True)
        serializer = SpitSerializer(spits, many=True)
        list = serializer.data
        list = transfer(list, request)
        return Response(list)

    # 6.4 发布吐槽
    def post(self, request):
        dict = request.data
        content = dict.get('content')
        if content is None:
            return None
        parent_id = dict.get('parent')

        if request.user.is_anonymous:
            if parent_id is None:
                Spit.objects.create(userid='anonymous', content=content)
                return Response('success')
            else:
                return None

        try:
            user = User.objects.get(username=request.user.username)
            avatar = user.avatar
            Spit.objects.create(userid=user.id, nickname=user.username, avatar=avatar, content=content,
                                parent_id=int(parent_id))
            if parent_id:
                spit = Spit.objects.get(id=parent_id)
                spit.comment += 1
                spit.save()
        except Exception as e:
            return None

        return Response()


# 6.2 收藏或取消收藏
class SpitCollectView(View):
    def put(self, request, id):
        try:
            redis_conn = get_redis_connection('default')
            collected_set = redis_conn.smembers('collected_%s' % request.user.id)
            collected_list = []
            for item in collected_set:
                collected_list.append(int(item))
            if int(id) in collected_list:
                redis_conn.srem('collected_%s' % request.user.id, id)
            else:
                redis_conn.sadd('collected_%s' % request.user.id, id)
        except Exception as e:
            return JsonResponse({'message': 200, 'success': 0})

        return JsonResponse({'message': 200, 'success': 1})


# 6.3 点赞或取消点赞
class SpitThumbupView(APIView):
    def put(self, request, id):
        try:
            spit = Spit.objects.get(id=id)
            redis_conn = get_redis_connection('default')
            thumbup_set = redis_conn.smembers('thumbup_%s' % request.user.id)
            thumbup_list = []
            for item in thumbup_set:
                thumbup_list.append(int(item))
            if int(id) in thumbup_list:
                redis_conn.srem('thumbup_%s' % request.user.id, id)
                spit.thumbup -= 1
                spit.save()
            else:
                redis_conn.sadd('thumbup_%s' % request.user.id, id)
                spit.thumbup += 1
                spit.save()
        except Exception as e:
            return Response({'message': 200, 'success': 0})

        return Response({'message': 200, 'success': 1})


# 6.5　吐槽详情
class SpitDetailView(APIView):
    def get(self, request, id):
        spit = Spit.objects.get(id=id)
        serializer = SpitSerializer(spit)
        dict = serializer.data
        list = []
        list.append(dict)
        list = transfer(list, request)
        return Response(list[0])


# 6.6 获取吐槽评论
class SpitCommentView(APIView):
    def get(self, request, id):
        spits = Spit.objects.filter(parent_id=id)
        serializer = SpitSerializer(spits, many=True)
        list = serializer.data
        list = transfer(list, request)
        return Response(list)


# class CommonView(View):
#     def post(self, request):
#         '''前端副文本编辑器上传图片'''
#         rec_data = request.FILES.get('upload')
#
#         # FastDFSStorage.exists(data)
#
#         ret = FastDFSStorage.save(self, name='name.jpg', content=rec_data, max_length=None)
#         image_url = FastDFSStorage.url(self, ret)
#         url = "http://www.1024.site:8080/upload_success.html?image_url=" + image_url + "&CKEditorFuncNum=1"
#
#         # http://127.0.0.1/upload_success.html?image_url=http://47.92.144.35:443/group1/M00/00/00/rBACxl3ggw2AZ1CbAAAo5jLCaQc72
#         # 73744&CKEditorFuncNum=1
#         return response.HttpResponseRedirect(url);